package com.lin.missyou.service;

import com.lin.missyou.bo.OrderMessageBO;
import com.lin.missyou.core.enumeration.OrderStatus;
import com.lin.missyou.exception.http.ParameterException;
import com.lin.missyou.exception.http.ServerErrorException;
import com.lin.missyou.model.Order;
import com.lin.missyou.repository.OrderRepository;
import com.lin.missyou.repository.SkuRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderCancelService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private SkuRepository skuRepository;

    /**
     * 取消订单
     * 归还库存
     *
     * @param
     */
//    @EventListener
    @Transactional
    public void cancel(OrderMessageBO orderMessageBO) {
        if (orderMessageBO.getOrderId() <= 0) {
            throw new ServerErrorException(9999);
        }
        this.cancel(orderMessageBO.getOrderId());

    }

    private void cancel(Long oid) {
        Order order = orderRepository.findById(oid)
                .orElseThrow(() -> new ServerErrorException(9999));

        int result = orderRepository.cancelOrder(oid);
        if (result != 1) {
            return;
        }
        order.getSnapItems()
                .forEach(i->{skuRepository.recoverStock(i.getId(), i.getCount().longValue()); } );
    }
}
